/*
 * WebServiceUtil.java Created on 2006-12-5
 * Copyright(c) 2006-2008 by vnv
 * ALL Rights Reserved.
 */
package cn.agiledata.bank.webService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.time.DateUtils;

import cn.agiledata.bank.common.service.NotifyUtil;
import cn.agiledata.bank.common.servlet.InitForString;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.hibernateBean.AccountBank;
import cn.agiledata.bank.hibernateBean.BankInfo;
import cn.agiledata.bank.hibernateBean.ListAccount;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.myspace.bean.AccountQueryBean;
import cn.agiledata.bank.webService.constant.IVRConstant;
import cn.agiledata.bank.webService.formbean.AccountListFormbean;
import cn.agiledata.bank.webService.formbean.BankFormbean;
import cn.agiledata.bank.webService.formbean.IVRRequest;
import cn.agiledata.bank.webService.formbean.IVRResponse;
import cn.agiledata.bank.webService.formbean.SubAccountFormbean;
import cn.agiledata.bank.webService.formbean.TransactionFormbean;

/**
 * some help method about webservice.
 * @time: 15:21:01
 * @author  maxianbo
 */
public class WebServiceUtil {
    /**
     * Get the subaccount frombean array from subaccount list.
     * @return subaccount frombean array.
     */
    public static SubAccountFormbean[] convertSubAccountArray4Collection(
        List subAccounts) {
        SubAccountFormbean[] subAccountArray = new SubAccountFormbean[subAccounts.size()];

        for (int i = 0; i < subAccounts.size(); i++)
            subAccountArray[i] = (SubAccountFormbean) subAccounts.get(i);

        return subAccountArray;
    }

    /**
     * Get the bank formbean array from bank list.
     * @return  bank formbean array.
     */
    public static BankFormbean[] convertSubBankArray4Collection(List banks) {
        BankFormbean[] bankArray = new BankFormbean[banks.size()];

        for (int i = 0; i < banks.size(); i++)
            bankArray[i] = (BankFormbean) banks.get(i);

        return bankArray;
    }

    /**
     * Get transaction formbean array from transaction list.
     * @return transaction frombean array.
     */
    public static TransactionFormbean[] convertTransactionArray4Collection(
        List Transactions) {
        TransactionFormbean[] transactionArray = new TransactionFormbean[Transactions.size()];

        for (int i = 0; i < Transactions.size(); i++)
            transactionArray[i] = (TransactionFormbean) Transactions.get(i);

        return transactionArray;
    }

	 /**
	  * check the login user info and other required field
	  * @param request
	  * @param response
	  * @param methodName
	  * @return
	  */
    public static boolean checkUser(IVRRequest request, IVRResponse response,
        String methodName) {
        String fields;

        /** check the request whether it is null */
        if (null == request) {
            response.setResult(IVRConstant.COMMON_USER_NOT_FIND);

            return false;
        }

        /** check the userid whether it is null or it is't value */
        //if ((null == request.getUserId()) || (request.getUserId() == "")) {
        //    response.setResult(IVRConstant.COMMON_USER_NOT_FIND);
        //
        //    return false;
        //}

        fields = getCheckFields4MethodName(methodName.toUpperCase());

        if (!checkRequest(request, response, fields)) {
            return false;
        }

        return true;
    }

    /**
    * check the login user info
    * @param request
    * @param response
    * @return
    */
    public static boolean checkUser(IVRRequest request, IVRResponse response) {
        String fields;

        /** check the request whether it is null */
        if (null == request) {
            response.setResult(IVRConstant.COMMON_USER_NOT_FIND);

            return false;
        }

        /** check the userid whether it is null or it is't value */
        if ((null == request.getUserId()) || (request.getUserId() == "")) {
            response.setResult(IVRConstant.COMMON_USER_NOT_FIND);

            return false;
        }

        return true;
    }

    // bleow method is mock caller

    /**
          * Create a mock object mock the caller :-)
          * @return
          */
    public static SubAccountFormbean[] getTestASArray() {
        SubAccountFormbean[] subAccountArray = new SubAccountFormbean[3];

        for (int i = 0; i < 3; i++) {
            SubAccountFormbean su = new SubAccountFormbean();
            su.setAccountid(String.valueOf(i));

            if (i == 0) {
                su.setBalance(new Double(123));
            }

            if (i == 1) {
                su.setBalance(new Double(222));
            }

            if (i == 2) {
                su.setBalance(new Double(2323));
            }

            subAccountArray[i] = su;
        }

        return subAccountArray;
    }

    /**
     *
     * @return
     */
    public static BankFormbean[] getMockBankArray() {
        BankFormbean[] bankArray = new BankFormbean[3];

        for (int i = 0; i < 3; i++) {
            BankFormbean bank = new BankFormbean();
            bank.setBankcode(String.valueOf(i));

            if (i == 0) {
                bank.setBankname(IVRConstant.BANK_NAME_CCB);
            }

            if (i == 1) {
                bank.setBankname(IVRConstant.BANK_NAME_ICBC);
            }

            if (i == 2) {
                bank.setBankname(IVRConstant.BANK_NAME_ABCHINA);
            }

            bankArray[i] = bank;
        }

        return bankArray;
    }

    /**
     * Get he mock transcation array.
     * @return the transaction array.
     */
    public static TransactionFormbean[] getMockTransactionArray() {
        TransactionFormbean[] transactionArray = new TransactionFormbean[3];

        for (int i = 0; i < 3; i++) {
            TransactionFormbean trans = new TransactionFormbean();
            trans.setTransid(String.valueOf(i));

            if (i == 0) {
                trans.setTransMoney(new Double(i));
            }

            if (i == 1) {
                trans.setTransMoney(new Double(i));
            }

            if (i == 2) {
                trans.setTransMoney(new Double(i));
            }

            transactionArray[i] = trans;
        }

        return transactionArray;
    }

    /**
     * Check the request parameter integrity
     * @param requet          the IVR request.
     * @param response        the webservice response.
     * @param checkedFileds   the checked fields string, this string is splilet by split
     *                        for example ("aaa,bbb,ccc,ddd") and so on.
     * @return
     */
    public static boolean checkRequest(IVRRequest request,
        IVRResponse response, String checkedFileds) {
        int splitNumber;
        String field;
        Object value;

        StringTokenizer stringToken = new StringTokenizer(checkedFileds,
                IVRConstant.CHECK_STRING_SPLIT_FLAG);
        splitNumber = stringToken.countTokens();

        try {
            for (int i = 0; i < splitNumber; i++) {
                field = stringToken.nextToken();
                value = PropertyUtils.getProperty(request, field);

                if (null == value) {
                    response.setResult(IVRConstant.COMMON_PARAMTER_DEFORMITY);

                    return false;
                } else {
                	if(value instanceof String) {
                		if("".equals(value)) {
                            response.setResult(IVRConstant.COMMON_PARAMTER_DEFORMITY);

                            return false;                			
                		}
                	}
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return true;
    }
    
    /**
     *
     * @param methodName
     * @return
     */
    public static String getCheckFields4MethodName(String methodName) {
        return (String) IVRConstant.checkMethodofFieldsMap.get(methodName.toUpperCase());
    }
    
    /**
     * Get the IVR User call type, whether it is a phone or    
     * @param telNumber
     * @return
     */
    public static String getPhoneORMobile4IVRTelphoneNumber(String telNumber){
    	
    	DateUtils dut = new DateUtils();
    	
    	return null;
    }
    
    /**
     *    
     * @param monthFristDateString
     * @return
     */
    public static String getMonthLastDate(String monthFristDateString){
    	
    	Date lastMonthFristDate;
    	Date monthLastDate;
    
    	SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd");
    	
    	try{
    		
    		Date monthFristDate = simp.parse(monthFristDateString);
    		Calendar c = Calendar.getInstance();
            c.setTime(monthFristDate);
            c.add(Calendar.MONTH, 1);
     
            lastMonthFristDate =  c.getTime();
            c.add(Calendar.DAY_OF_MONTH,-1);
            monthLastDate = c.getTime();
            
            return simp.format(monthLastDate);
            
    	}catch(Exception ex){
    		ex.printStackTrace();
    		return null;
    	}
   
    }
    
    /**
     * Convert subaccount list to array.   
     * @param subaccounts 	the 
     * @return the transaction array. 
     */
    public static SubAccountFormbean[] convertList2SubAccounts(List subaccounts){
    	SubAccount subaccount;
    	SubAccountFormbean[] subAccounts = new SubAccountFormbean[subaccounts.size()];
    	for(int i = 0 ; i < subaccounts.size(); i++)
    	{
    		SubAccountFormbean sub = new SubAccountFormbean();
    		subaccount = (SubAccount)subaccounts.get(i);
    		sub.setAccountid(subaccount.getId().toString());
    		sub.setAccountname(subaccount.getAccountName());
    		sub.setBalance(subaccount.getAccountBalance().getBalance());
    		subAccounts[i] = sub;
    	}
    	return subAccounts;
    	
    }
    
    /**
     * Convert   
     * @param transactions
     * @return
     */
    public static TransactionFormbean[] convertList2Transactions(List transactions){
    	
    	AccountQueryBean transaction;
    	TransactionFormbean[] trans = new TransactionFormbean[transactions.size()];
		List listId =InitForString.getListId("TRANS_STATUS");
		List listName=InitForString.getListName("TRANS_STATUS");  	
    	for(int i = 0 ; i < transactions.size(); i++)
    	{
    		TransactionFormbean tranFormbean = new TransactionFormbean();
    		transaction = (AccountQueryBean)transactions.get(i);
    		tranFormbean.setTransid(transaction.getTransId());	//交易编号
    		tranFormbean.setTransMoney(transaction.getAmount());	//金额
    		tranFormbean.setActionType(transaction.getActionType());	//交易类型
    		tranFormbean.setFee(transaction.getFee());	//费用
    		if(transaction.getPayMode().equals("收")) {
    			tranFormbean.setPayMode("1");//收
    		} else {
    			tranFormbean.setPayMode("-1");//付
    		}
    		
    		//tranFormbean.setOtherAccount(transaction.getOtherAccountEmail().replaceAll("@", "~"));	//交易对方
    		tranFormbean.setOtherAccount(transaction.getOtherAccount().replaceAll("@", "~"));//交易对方
    		if (listName == null || listId==null)
    			return null;
    		for (int j = 0; j < listId.size(); j++) {
    			if(listId.get(j).equals(transaction.getTransStatus())) {
    				tranFormbean.setTransStatus(listName.get(j).toString());	//交易状态
    				break;
    			}
    		}
    		tranFormbean.setDate(DateUtil.date2String(transaction.getDate(), "yyyy-MM-dd-HH-mm"));	//交易日期
    		trans[i] = tranFormbean;
    	}
    	
    	return trans;
    }
    
    /**
     * Convert   
     * @param transactions
     * @return
     */
    public static TransactionFormbean[] convertList2WaitTransactions(List transactions){
    	
    	AccountQueryBean transaction;
    	TransactionFormbean[] trans = new TransactionFormbean[transactions.size()];
		List listId =InitForString.getListId("TRANS_STATUS");
		List listName=InitForString.getListName("TRANS_STATUS");
    	for(int i = 0 ; i < transactions.size(); i++)
    	{
    		TransactionFormbean tranFormbean = new TransactionFormbean();
    		ListAccount account = (cn.agiledata.bank.hibernateBean.ListAccount)transactions.get(i);
    		tranFormbean.setTransid(account.getTranId());	//交易编号
    		tranFormbean.setTransMoney(account.getAmount());	//交易金额
    		//tranFormbean.setOtherAccount(account.getEmail()==null?account.getMobile():account.getEmail().replaceAll("@", "~"));	//交易对方
    		
    		tranFormbean.setOtherAccount(account.getName()==null?(account.getEmail()==null?account.getMobile():account.getEmail()):account.getName());	//交易对方
    		tranFormbean.setOtherAccount(tranFormbean.getOtherAccount().replaceAll("@", "~"));
    		tranFormbean.setTransTrade(account.getTrade());	//交易模式
    		if(account.getComeOrGo().equals("0")) {
    			tranFormbean.setPayMode("-1");	//收/付
    		}
    		if(account.getComeOrGo().equals("1")) {
    			tranFormbean.setPayMode("1");	//收/付
    		}
    		
    		if (listName == null || listId==null)
    			return null;
    		for (int j = 0; j < listId.size(); j++) {
    			if(listId.get(j).equals(account.getTranStatus())) {
    				tranFormbean.setTransStatus(listName.get(j).toString());	//交易状态
    				break;
    			}
    		}    
    		Date beginDate = DateUtil.string2Date(account.getBeginDate());
    		
    		tranFormbean.setDate(DateUtil.date2String(beginDate, "yyyy-MM-dd-HH-mm"));	//交易日期
    		
    		Date updateDate = DateUtil.string2Date(account.getUpdateDate());
    		
    		int[] leftTime = NotifyUtil.getPermissionLeftDHM(updateDate, account.getTranStatus());
    		tranFormbean.setLeftDate(String.valueOf(leftTime[0])+"-"+String.valueOf(leftTime[1])+"-"+String.valueOf(leftTime[2]));
    		
    		trans[i] = tranFormbean;
    	}
    	
    	return trans;
    }
    /**
     *    
     * @param banks
     * @return
     */
    public static BankFormbean[] convertList2Banks(List banks){
    
    	BankFormbean bank;
    	BankFormbean[] bankarray = new BankFormbean[banks.size()];
    	BankInfo bankinfo;
    	for(int i = 0 ; i < banks.size(); i++)
    	{
    		bankinfo = (BankInfo)banks.get(i);
    		bank = new BankFormbean();
    		bank.setBankcode(bankinfo.getBankCode());
    		bank.setBankid(bankinfo.getBankId());
    		bank.setBankname(bankinfo.getBankName());
    		bankarray[i] = bank;
    	}
    	return bankarray;
    }
    
    public static AccountListFormbean[] convertList2AccountList(List list) {
    	AccountListFormbean[] beans = new AccountListFormbean[list.size()];
    	for(int i=0;i<list.size();i++) {
    		AccountBank ab = (AccountBank)list.get(i);
    		AccountListFormbean bean = new AccountListFormbean();
    		bean.setSeq(String.valueOf(i+1));
    		bean.setId(ab.getId().toString());
    		bean.setAccountId(ab.getAccountId());
    		bean.setBankAlias(ab.getBankAlias());
    		beans[i] = bean;
    	}
    	return beans;
    }
    
    
   /**
    *    
    * @param args
    */
    public static void main(String[] args){
    	String testDate = "2006-01-01";
    }
  
}
